<template>
  <div class="main">
    <!--<van-nav-bar title="地图影像" />-->
    <!--<div class="tools" v-if="false">-->
    <div class="tools" v-if="true">
      <div class="celiang" @click="showTools">
        <i class="iconfont icon-chizi"></i>
        <span>测量</span>
      </div>
      <div class="celiang" @click="doPatrol">
        <i class="iconfont icon-qingchu" style="font-size: 20px;padding-top: 2px"></i>
        <span>巡护</span>
      </div>
    </div>
  </div>
  <div id="map"></div>
</template>

<script setup>
import {onMounted} from "vue"
import L from "leaflet"
import 'leaflet.pm';
import 'leaflet.pm/dist/leaflet.pm.css';
import * as turf from '@turf/turf'

let map
// 测量坐标
let polylinePoints = []
let polygonPoints = []
let circlePoint = []
// 测量结果
let polygonArea
let lineLength
// marker
let viewIcon
// 要素合计
let viewSpotLayer

onMounted(()=>{
  initLeaflet()
})

const initLeaflet = () => {
  map = L.map("map").setView([41.7958,123.3301], 7)
  // 卫星影像
  L.tileLayer("http://t7.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=4b418047223bdd0dfc7cbdb7dfe1d3e6",{
    attribution: '&copy;沈阳浩宇地理信息有限公司',
    maxZoom: 18,
    subdomains: "1234",
  }).addTo(map)
  // 卫星影像注记
  L.tileLayer("http://t7.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=4b418047223bdd0dfc7cbdb7dfe1d3e6",{
    attribution: '&copy;沈阳浩宇地理信息有限公司',
    maxZoom: 18,
    subdomains: "1234",
  }).addTo(map)

  const shiliang = {
    "矢量注记": L.tileLayer('http://t7.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=4b418047223bdd0dfc7cbdb7dfe1d3e6', {
      maxZoom: 18,
      attribution: '&copy;沈阳浩宇地理信息有限公司',
      subdomains: "1234",
    }),
    "影像图层": L.tileLayer('http://t7.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=4b418047223bdd0dfc7cbdb7dfe1d3e6', {
      maxZoom: 18,
      attribution: '&copy;沈阳浩宇地理信息有限公司',
      subdomains: "1234",
    }),
  }

  const baseLayers = {
    "影像图层": L.tileLayer('http://t7.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=4b418047223bdd0dfc7cbdb7dfe1d3e6 ', {
      maxZoom: 18,
      attribution: '&copy;沈阳浩宇地理信息有限公司',
      subdomains: "1234",
    }),

    '矢量图层': L.tileLayer('http://t7.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=4b418047223bdd0dfc7cbdb7dfe1d3e6', {
      maxZoom: 18,
      attribution: '&copy;沈阳浩宇地理信息有限公司',
      subdomains: "1234",
    })
  }

  const layerControl = L.control.layers(baseLayers, shiliang, {
    position: 'topleft',
    collapsed: true
  }).addTo(map)

  viewIcon = L.icon({
    iconUrl: require("@/assets/images/Map/Marker.png"),
    iconSize: [40, 40],
    // iconAnchor: [0,0],
    // popupAnchor: [0, -13]
  })
  // loadWMS()

  // 初始化合集
  viewSpotLayer = new L.featureGroup([])
}
const initPM = () => {
  // 配置leaflet.pm插件
  map.pm.setLang("zh")
  map.pm.addControls({
    position: "topleft",
    drawPolygon: true, //绘制多边形
    drawMarker: false, //绘制标记点
    drawCircleMarker: false, //绘制圆形标记
    drawPolyline: true, //绘制线条
    drawRectangle: false, //绘制矩形
    drawCircle: false, //绘制圆圈
    editMode: false, //编辑多边形
    dragMode: false, //拖动多边形
    cutPolygon: false, //添加⼀个按钮以删除多边形⾥⾯的部分内容
    removalMode: true, //清除多边形
  })

  map.pm.setPathOptions({
    color: "orange",
    fillColor: "green",
    fillOpacity: 0.4,
  })

  const options = {
    // 连接线标记之间的线
    templineStyle: {
      color: "red",
    },
    // 提⽰线从最后⼀个标记到⿏标光标的线
    hintlineStyle: {
      color: "red",
      dashArray: [5, 5],
    },
    // 绘制完成的样式
    pathOptions: {
      color: "orange",
      fillColor: "green",
    },
  }

  // 激活绘制多边形功能-1、单独设置某个模式的样式
  map.pm.enableDraw("Polygon", options)

  // 启用绘制--多边形功能
  map.pm.enableDraw("Polygon", {
    snappable: true, //启⽤捕捉到其他绘制图形的顶点
    snapDistance: 20, //顶点捕捉距离
  })

  // 关闭绘制--注意也可以关闭其他模式的绘制功能
  map.pm.disableDraw("Polygon")

  map.on("pm:create", (e) => {
    // console.log(e, "绘制完成时调⽤")
    // 画圆
    if (e.shape === "Circle") {
      const graphic = LMapUtil.getGraphics(e)
      circlePoint = e.layer._latlngs
       //画线
    } else if (e.shape === "Line") {
      polylinePoints = []
      for(let i = 0; i < e.layer._latlngs.length; i++){
        polylinePoints.push([e.layer._latlngs[i].lat,e.layer._latlngs[i].lng])
      }
      // 测距
      getDistance()
      //画面
    } else if (e.shape === "Polygon"){
      for(let i = 0; i < e.layer._latlngs[0].length; i++){
        polygonPoints.push([e.layer._latlngs[0][i].lat,e.layer._latlngs[0][i].lng])
      }
      polygonPoints.push([e.layer._latlngs[0][0].lat,e.layer._latlngs[0][0].lng])
      //绘制结束侧面积
      getPolygonArea()
    }
  })

  map.on("pm:globalremovalmodetoggled", (e) => {
    // 清空时也清空坐标
    polylinePoints = []
    polygonPoints = []
    if(polylineFeature){
      map.removeLayer(polylineFeature)
    } else if(pointFeature) {
      map.removeLayer(pointFeature)
    }
  })
}
// 加载矢量
const loadWMS = () => {
  const wmsLayer = L.tileLayer.wms('http://www.hydlxx.com:8080/geoserver/hywebgis/wms', {
    layers: 'hywebgis:sihuanPoline4490', // 替换为自己的图层
    format: 'image/png',
    transparent: true,
    noCache: Math.random() // 设置随机数作为noCache参数的值
  })
  // 将WMS图层添加到地图上
  wmsLayer.addTo(map)
}

// 显示测量工具
const showTools = () => {
  initPM()
}

// 测距
let pointFeature
const getPolygonArea = () => {
  if(pointFeature) {
    map.removeLayer(pointFeature)
  }
  const polygon = turf.polygon([polygonPoints])
  const a = turf.area(polygon)/4046.8564
  polygonArea = a.toFixed(2)
  console.log(polygonPoints)
  pointFeature = new L.Marker(polygonPoints[polygonPoints.length-1]).addTo(map).bindPopup(`<b>选中面积为</b><br>${polygonArea}亩`).openPopup()

  pointFeature.addTo(viewSpotLayer)
}

// 测距
let polylineFeature
const getDistance = () => {
  if(polylineFeature) {
    map.removeLayer(polylineFeature)
  }
  // 获取长度
  const line = turf.lineString(polylinePoints)
  lineLength = turf.length(line, {units: 'kilometers'}).toFixed(2)
  // 添加marker
  polylineFeature = new L.Marker(polylinePoints[polylinePoints.length-1]).addTo(map).bindPopup(`<b>距离</b><br>${lineLength}千米`).openPopup()
  // window.polylineFeature = polylineFeature
}

// 巡护
const doPatrol = () => {
  console.log(window.polylineFeature)
}
</script>

<style scoped lang="less">
.main{
  .title{
    font-size: 30px;
  }
  .tools{
    position: absolute;
    top: 120px;
    left: 640px;
    z-index: 999;
    display: flex;
    flex-direction: column;
    .celiang{
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      border-radius: 7px;
      height: 75px;
      width: 75px;
      background-color: #fff;
      border: 1px solid rgba(0,0,0,.5);
      box-shadow: 0 0 2px rgba(0,0,0,.9);
      margin-bottom: 10px;
      .iconfont {
        margin: 0 auto;
        font-size: 45px;
        color: darkgray;
        //line-height: 80px;
      }
      span{
        font-size: 20px;
      }
    }
    .quandi{
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      border-radius: 7px;
      height: 81px;
      width: 90px;
      background-color: #fff;
      border: 1px solid rgba(0,0,0,.5);
      box-shadow: 0 0 2px rgba(0,0,0,.9);
      padding-top: 5px;
      .iconfont {
        margin: 0 auto;
        font-size: 45px;
        color: darkgray;
        //line-height: 80px;
      }
      span{
        font-size: 25px;
      }
    }
  }
}
#map{
  //margin-top: 46px;
  height: 94%;
  width: 100vw;
}
:deep(.button-container.active .leaflet-pm-actions-container){
 margin-left: 35px;
}
</style>